<template>
  <div class="register-container">
    <el-card class="register-box">
      <h2 class="title" style="text-align: left;">注册</h2>
      <el-form label-width="100px">
        <h4 style="text-align: left;" label="用户名">
          用户名:<el-input v-model="form.username" />
        </h4>
        <h4 style="text-align: left;" label="密码">
          密码:<el-input v-model="form.password" type="password" />
        </h4>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">注册</el-button>
          <el-button @click="goToLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const form = ref({
  username: '',
  password: ''
});
const registerForm = ref<any>(null);

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

const onSubmit = async () => {
  try {
    await registerForm.value?.validate();
    const response = await axios.post(`${API_BASE_URL}/auth/register`, form.value);
    localStorage.setItem('token', response.data.token);
    localStorage.setItem('userId', response.data.userId);
    router.push({
      path: '/login',
      query: {
        username: form.value.username,
        password: form.value.password
      }
    });
  } catch (error: any) {
    if (error.response?.status === 409) {
      ElMessage.error('用户名已存在');
    } else {
      ElMessage.error(error.response?.data?.message || '注册失败');
    }
  }
};

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 500px;
  padding: 20px;
}

.title {
  margin-bottom: 20px;
  font-size: 1.5em;
  color: #303133;
}

.el-form-item {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .register-box {
    padding: 15px;
  }

  .el-form-item__label {
    width: 100% !important;
    text-align: left;
  }

  .el-form-item__content {
    margin-left: 0 !important;
  }
}
</style> 